<template>
  <div class="box">
    <div id="huan_zhuang_tu" ref="huan_zhuang_tu" @click="clickChart"></div>

    <span class="unit" v-if="isShowUnit">单位: {{ unit }}</span>
  </div>
</template>

<script setup lang="js">
import * as echarts from "echarts"
import { ref, reactive, watch, onMounted } from 'vue'

const props = defineProps({
  value: Object,
  isShowUnit: null
})
const emit = defineEmits(['emitChartParams'])

const huan_zhuang_tu = ref(null)

const unit = ref('')
const options = reactive({
  tooltip: {
    trigger: "item",
    show: false,
  },
  // 提示
  tooltip: {
    trigger: "item",
    show: true,
  },
  legend: {
    top: "5%",
    left: "center",
    selectedMode: false,
    color: '#fff',
    show: false
  },
  series: [
    {
      type: "pie",
      color: [
        'rgb(137, 240, 106)',
        'rgb(106, 240, 177)',
        'rgb(9, 117, 240)',
        'rgb(227, 233, 240)',
        '#4af5e7',
        'rgb(245, 138, 221)',
        'rgb(224, 85, 85)',
      ],
      radius: ["40%", "46%"],
      center: ["50%", "50%"],
      // adjust the start angle
      startAngle: 180,
      label: {
        color: '#fff',
        fontSize: 16,
        formatter: function (params) {
          return params.name + `{span|${params.value}}`
        },
        rich: {
          span: {
            color: '#fff',
            fontSize: '16px',
            fontWeight: '500',
            fontFamily: '',
          }
        }
      },
      data: [],
      itemStyle: {
        borderRadius: 10,
        borderColor: 'rgb(0, 0, 0, 0)',
        borderWidth: 6,
      },
    },
  ]
})

watch(() => props.value,
  (newVal, oldVal) => {
    unit.value = newVal.unit
    let data = newVal.data
    options.series[0].data = data
    if (data) {
      initChart()
    }
  },
  {
    deep: true,
    // immediate: true
  }
)

onMounted(() => {
  initChart()
})

function initChart() {
  let chart = echarts.init(huan_zhuang_tu.value);

  chart.on('click', params => {
    clickChart(params)
  })

  chart.setOption(options)
  // window.onresize = huan_zhuang_tu.resize;
}

function clickChart(params) {
  emit('emitChartParams', params.data)
}
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  position: relative;
}

#huan_zhuang_tu {
  width: 100%;
  height: 100%;
}

.unit {
  position: absolute;
  left: 10px;
  bottom: 0px;
  color: #fff;
  font-size: 14px;
}
</style>
